# -*- coding: utf-8 -*-

import logging
import traceback

from GKModel import TutorMatch
from GKModel import OTSHelper
from utils import build_json
from utils import parse_event


def handler(event, context):
    logger = logging.getLogger()
    try:
        http_method, query_parameters, path_parameters, body, client_token, deploy_config = parse_event(event)
        ots_client = OTSHelper.create_client()
        tutor_match = TutorMatch.new(
            ots_client=ots_client,
            deploy_config=deploy_config,
            logger=logger,
            client_token=client_token
        )
        if http_method == 'POST':
            match_type = body['type']
            name = body['name']
            phone = body['phone']
            requirement = body['requirement'] if 'requirement' in body else ''
            client_token = tutor_match.create_match(
                match_type=match_type,
                name=name,
                phone=phone,
                requirement=requirement
            )

            return build_json(0, 'Success', {}, client_token)
        return build_json(0, 'Success', {}, '')

    except ValueError as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(e.args[0], e.args[1], None)
    except Exception as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(-1, str(e), None)
